<?php

namespace addons\csmitsm\library\xcore\xcore\utils;

use addons\csmitsm\library\xcore\xcore\XcException;
use Exception;
use ReflectionClass;

class XcReflectionClassUtils
{
    // public static function assertClsnameMethodname($clsname, $methodname)
    // {
    //     if (class_exists($clsname)) {
    //         if (method_exists($clsname, $methodname)) {
    //             return;
    //         } else {
    //             throw new XcException("类 {$clsname} 存在，但方法 {$methodname} 不存在。");
    //         }
    //     } else {
    //         throw new XcException("类 {$clsname} 不存在。");
    //     }
    // }

    public static function newInstance($clsname)
    {
        $reflectionClass = new ReflectionClass($clsname);
        return $reflectionClass->newInstance();
    }

    public static function callMethod($clsname, $methodname, ...$params)
    {
        try {
            $reflectionClass = new ReflectionClass($clsname);
            $object = $reflectionClass->newInstance();
            $reflectionMethod = $reflectionClass->getMethod($methodname);
            return $reflectionMethod->invoke($object, ...$params);
        } catch (Exception $e) {
            throw new XcException("{$clsname}::{$methodname}不存在");
        }
    }

    public static function assertMethodExists($clsname, $methodname)
    {
        if (!method_exists($clsname, $methodname)) {
            throw new XcException("{$clsname}::{$methodname}不存在");
        }
    }
}
